#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
from datetime import datetime

from conn.MyLogs import MyLogs
from hcmv.beans.FoodCatalogObj import FoodCatalogObj

start = 1  # 起始值
end = 100  # 结束值


class FoodCatalogsService:
    std_array = {}

    def __init__(self, conn):
        self.conn = conn

    def fetch(self, param):
        try:
            count_sql = f" SELECT count(`id`) FROM `mem_food_catalogs` WHERE 1=1 %s"
            fetch_sql = f" SELECT `id`,`name`,`classification`,`unit_content_index`,`heat`,`measurement_unit`,`calorie`,`label_recognition`,`explain` " \
                        f" FROM `mem_food_catalogs` WHERE 1=1 %s "
            where_sql = ""
            if len(param['key']) > 0:
                where_sql = where_sql + f" AND CONCAT(`name`,`classification`) like CONCAT('%',\'{param['key']}\','%') "
            int_begin = 0
            if int(param['pageNum']) > 1:
                int_begin = (int(param['pageNum']) - 1) * int(param['pageSize'])
            elif int(param['pageNum']) == 1:
                int_begin = 0 * int(param['pageSize'])
            where_sql_no_limit = where_sql
            data_total = self.conn.sql_fetch(count_sql % where_sql_no_limit)
            where_sql_limit = where_sql+f" ORDER BY `classification` ASC,`unit_content_index` DESC LIMIT {int_begin}, {int(param['pageSize'])}"
            data_list = self.conn.sql_fetch(fetch_sql % where_sql_limit)
            items = []
            if len(data_list) > 0:
                items = [FoodCatalogObj.load_db_2_dict(data=item) for item in data_list]
            return {"code": 200, "data": items, "total": data_total[0][0]}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    def fetch_one(self, food_id):
        if int(food_id) ==0:
            return {"code": 200, "data": FoodCatalogObj.init_dict()}
        fetch_sql = f" SELECT `id`,`name`,`classification`,`unit_content_index`,`heat`,`measurement_unit`,`calorie`,`label_recognition`,`explain`" \
                    f" FROM `mem_food_catalogs` WHERE 1=1 " \
                    f" AND `id` = \'{food_id}\'"
        try:
            items = self.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                res = [FoodCatalogObj.load_db_2_dict(item) for item in items]
                return {"code": 200, "data": res[0]}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def add_food_catalog(self, foodCatalog: object):
        try:
            add_check = self.count_one(id=foodCatalog['id'])
            if add_check:
                return {"code": 203, "data": None}
            insert_sql = f" INSERT INTO `mem_food_catalogs` ({FoodCatalogObj.to_string(False)}) " \
                         " VALUES ( %s )" % FoodCatalogObj.concat_datas(foodCatalog)
            self.conn.sql_commit(insert_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def update_food_catalog(self, foodCatalog, food_id):
        # 获取当前时间
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        try:
            add_check = self.count_one(id=foodCatalog['id'])
            if not add_check:
                return {"code": 404, "data": None}
            old_data = self.fetch_one(food_id=food_id)
            update_str = FoodCatalogObj.split_params(foodCatalog)
            update_sql = f" UPDATE `mem_food_catalogs` SET %s, `update_date`=\'{current_time}\'" \
                         f" WHERE `id`= \'%s\'" % (update_str, food_id)
            self.conn.sql_commit(update_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def drop_food_catalog(self, food_id):
        # 获取当前时间
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        add_check = self.count_one(id=food_id)
        if not add_check:
            return {"code": 404, "data": None}
        execute_SQL = f" DELETE FROM `mem_food_catalogs` " \
                      f" WHERE `id` = \'{food_id}\'"
        self.conn.sql_commit(execute_SQL)
        return {"code": 200, "data": None}

    def count_one(self, id) -> bool:
        fetch_sql = f"SELECT count(`id`) FROM `mem_food_catalogs` WHERE 1 = 1 " \
                    f" AND `id` = \'{id}\'"
        try:
            items = self.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                return items[0][0] > 0
            return False
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}


    def updateCustDinner(self, custDinner) :
        try:
            MyLogs.logger.info(custDinner)
            update_sql = f"UPDATE sys_dict SET `val`= '%s' WHERE 1=1 AND `key_eng`='custDinner'" % custDinner
            self.conn.sql_commit(update_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
            return {"code": 500, "data": None}

    def custom_choose_opt_data(self, flg, key):
        try:
            where_sql = ""
            fetch_sql = f" SELECT `id`,`key`,`key_eng`,`col`,`val`, `add_time` FROM `sys_dict` WHERE 1=1 %s "
            if flg is not None and len(flg) > 0:
                where_sql += f" AND `key_eng` =  '{flg}'"
            if key is not None and len(key) > 0:
                where_sql += f"and `val` like CONCAT(\"%\",\"{key}\",\"%\") and key_eng in (\"protein\",\"carbonWater\",\"fat\",\"vitamin\")"
            data_list = self.conn.sql_fetch(fetch_sql % where_sql)
            if len(data_list) > 0:
                return {"code": 200, "data": json.loads(data_list[0][4])}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}